use std::io::Error;
use super::buffer::Buffer;
use super::terminal::{Position, Size, Terminal};

const APPNAME: &str = env!("CARGO_PKG_NAME");
const APPVERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Default)]
pub struct View {
    buffer: Buffer,
}
impl View {
    pub fn load(&mut self, file_name: Option<&String>) -> Result<(), Error> {
        self.buffer = Buffer::load(file_name);
        self.render()
    }

    pub fn render(&mut self) -> Result<(), Error> {
        let Size { width, height } = Terminal::size()?;

        for row_number in 0..height - 1 {
            Terminal::clear_line()?;
            //let row_number = row_number as usize;
            if let Some(line) = self.buffer.lines.get(row_number) {
                Terminal::print(line)?;
            } else if row_number == height - 2 {
                self.draw_welcome_message(width, height)?;
            } else {
                Self::draw_empty_row()?;
            }
            Terminal::print("\r\n")?;
        }
        Terminal::execute()?;
        Ok(())
    }
    pub fn draw_welcome_message(
        &self,
        screen_width: usize,
        screen_height: usize,
    ) -> Result<(), Error> {
        let welcome_msg = format!("{APPNAME} {APPVERSION} @copyright");
        let start_index = (screen_width - welcome_msg.len() as usize) / 2;
        Terminal::move_caret(Position {
            col: start_index,
            row: screen_height - 2,
        })?;

        Terminal::print(&welcome_msg)?;
        // Terminal::execute()?;
        Ok(())
    }
    fn draw_empty_row() -> Result<(), Error> {
        Terminal::print("~")?;
        Ok(())
    }
}
